package com.hp.team.bookstore.dbutil.init;

import java.io.File;
import java.io.FileInputStream;

import com.hp.team.bookstore.dbutil.Utils;
import com.hp.team.bookstore.dbutil.dao.DAOFactory;
import com.hp.team.bookstore.dbutil.dao.HibernateUtil;
import com.hp.team.bookstore.dbutil.dao.catalog.ProductHibernateDAO;
import com.hp.team.bookstore.model.catalog.Product;

public class ProductInitializer {

	private static final String IMAGE_UPLOAD_DIR = "images/";

	private static ProductHibernateDAO productDAO;

	static {
		DAOFactory daoFactory = new DAOFactory();
		productDAO = daoFactory.getProductDAO();
	}

	public static void init() {

		productDAO.setSession(HibernateUtil.getSessionFactory().getCurrentSession());
		HibernateUtil.beginWriteTransaction();

		for (int i = 0; i < 10; i++) {
			Product product = createProduct(i);
			productDAO.makePersistent(product);
		}

		HibernateUtil.commitTransaction();
	}

	public static Product createProduct(long id) {

		File file = new File(IMAGE_UPLOAD_DIR + "thumb" + id + ".gif");
		byte[] imageBytes = new byte[(int) file.length()];

		try {
			FileInputStream fileInputStream = new FileInputStream(file);
			// convert file into array of bytes
			fileInputStream.read(imageBytes);
			fileInputStream.close();
		} catch (Exception e) {
			e.printStackTrace();
		}

		Product product = new Product();
		product.setName("Book #" + id);
		product.setDescription("This is a long description of book #" + id);
		product.setAuthor("Author #" + (id + 1) / 2);
		product.setPublisher("Publisher #" + (10 - id) / 2);
		product.setIsbn("ISBN #" + id);
		product.setPrice(Utils.generateRandomNumber(5, 50));
		product.setImage(imageBytes);

		return product;
	}

	public static void main(String[] args) {
		UserInitializer.init();
	}

}
